package com.huanzhidadi.single.produceconsumer;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadLocalRandom;

class Producer implements Runnable {

    private final BlockingQueue queue;

    Producer(BlockingQueue q) {
        queue = q;
    }

    public void run() {
        try {
            while (true) {
                Thread.sleep(2000);
                queue.put(produce());
                System.out.println("queue大小:" + queue.size());
            }
        } catch (InterruptedException ex) {
            System.out.println(ex);
        }
    }
    Object produce() {
        int i = ThreadLocalRandom.current().nextInt(10);
        System.out.println("生产:" + i);
        return i;
    }
}

class Consumer implements Runnable {

    private final BlockingQueue queue;

    Consumer(BlockingQueue q) {
        queue = q;
    }

    public void run() {
        try {
            while (true) {
                Thread.sleep(3000);
                consume(queue.take());
            }
        } catch (InterruptedException ex) {
            System.out.println(ex);
        }
    }
    void consume(Object x) {
        System.out.println(this.hashCode() + "消费：" + x);
    }
}

public class BlockingQueueTest {
    public static void main(String[] args) {
        ThreadLocalRandom random = ThreadLocalRandom.current();
        List<Integer> integerList = new ArrayList<>();
        for (int i=0; i<7; i++) {
            integerList.add(random.nextInt(10));
        }
        BlockingQueue q = new ArrayBlockingQueue(10, false, integerList);
        Producer p = new Producer(q);
        Consumer c1 = new Consumer(q);
        Consumer c2 = new Consumer(q);
        new Thread(p).start();
        new Thread(c1).start();
        new Thread(c2).start();
    }
}